<?php
namespace frontend\modules\Oauth\controllers;

use Yii;
use yii\base\Exception;
use yii\helpers\ArrayHelper;
use frontend\controllers\RestController;
use frontend\modules\Oauth\services\UserService;
use yii\helpers\Json;
use yii\base\DynamicModel;

/**
 * Class IndexController
 * @package frontend\modules\Oauth\controllers
 */
class IndexController extends RestController
{
    /**
     * Oauth授权入口
     *
     * @return mixed
     * @throws
     */
    public function actionIndex()
    {
        $form = DynamicModel::validateData([
            'clientId' => Yii::$app->getRequest()->get('client_id'),
            'redirect' => Yii::$app->getRequest()->get('redirect'),
        ],[
            [['clientId','redirect'], 'required'],
        ]);
        if ($form->hasErrors()) {
            return self::failureResponse(500,current($form->getFirstErrors()));
        }
        // 校验必须参数
        try{
            $clientId   = Yii::$app->request->get('client_id'); //业务方标识
            $inputScope = Yii::$app->request->get('scope',2);
            $redirect   = Yii::$app->request->get('redirect');
            $redirect   = urldecode($redirect);
            // $redirect 检测是否白名单
            if(!UserService::checkWhite($redirect)){
                return static ::failureResponse(500,'回调域名未添加白名单') ;
            }
            // 存入redis 生成key
            $rt         = md5($redirect);
            UserService::setCache($rt,$redirect,120);
            $instance   = UserService::getInstance($clientId);
            $config     = ArrayHelper::merge(Yii::$app->request->get(),UserService::getPartner());
            // 拼接固定回调地址 & 参数
            $redirectUrl = Yii::$app->urlManager->createAbsoluteUrl('oauth/index/callback?client_id='.$clientId.'&scope='.$inputScope.'&rt='.$rt);
            $config['callBackUrl']   = $redirectUrl;
            $oauthUrl = $instance->getOauth2AuthorizeUrl($config);
            if(!$oauthUrl){
                return static ::failureResponse(500,'链接生成失败') ;
            }
            return header('Location: '.$oauthUrl);
        }catch (\Exception $exception){
            return static ::failureResponse(500,$exception->getMessage()) ;
        }
    }

    /**
     * @throws
     * 处理Oauth授权后的回调
     */
    public function actionCallback()
    {
        try{
            $clientId   = Yii::$app->request->get('client_id'); //业务方标识
            $rt         = Yii::$app->request->get('rt'); //回调地址key
            // 根据rt获取跳转地址
            $redirectUrl = UserService::getCache($rt);
            if(!$redirectUrl){
                throw new Exception('获取业务回调地址异常');
            }
            $instance   = UserService::getInstance($clientId);
            $params     = ArrayHelper::merge(Yii::$app->request->get(),UserService::getPartner());
            $ticket     = $instance->oauthCallBack($params);
            // 缓存存入redis
            if(!ArrayHelper::getValue($ticket,'cacheData')){
                throw new Exception('获取用户信息失败');
            }
            // 用户信息存入redis
            UserService::setCache($ticket['cacheKey'],Json::encode($ticket['cacheData'],JSON_UNESCAPED_UNICODE),180);
            if(strpos($redirectUrl,'?') > 0 ){
                $redirectUrl .= '&';
            }else{
                $redirectUrl .= '?' ;
            }
            $redirectUrl .= 'ticket='.$ticket['cacheKey'] ; // 拼接参数
            // 跳转回源站 带上参数
            return header('Location: '.$redirectUrl);
        }catch (\Exception $exception){
            return self ::failureResponse(500,$exception->getMessage()) ;
        }
    }

    /**
     * @throws
     * 接收ticket参数 然后调用接口拉取用户信息
     */
    public function actionTest()
    {
        $ticket = Yii::$app->request->get('ticket');
        $userData = UserService::getCache($ticket);
        if(!$userData){
            return static ::failureResponse(500,'ticket获取数据失败') ;
        }
        $userData = Json::decode($userData);
        return self::successResponse($userData) ;
    }
}
